package controller;

import java.io.IOException;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import model.Person;
import model.UserAccount;
import util.Log;
import validator.PersonValidator;
import web.JSONMessage;
import db.ImbiConnection;
import facade.PersonFacade;

public class PersonManageController extends HttpServlet{
	private static final long serialVersionUID = 1L;
	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		UserAccount u = (UserAccount)request.getSession().getAttribute("user");
		if(u != null){
			if(request.getParameter("delete")!= null){
				deletePerson(request, response, u);
			} else addPerson(request, response, u);
		}		
	}
	private void deletePerson(HttpServletRequest request,
			HttpServletResponse response, UserAccount u) throws IOException {		
		try{
			int id = Integer.parseInt(request.getParameter("id"));		
			Person p = ImbiConnection.getPersonDAO().find(id);
			if(p != null){
				PersonFacade.deletePerson(p);
				response.getWriter().write(JSONMessage.message("Person and related data deleted!"));
				Log.write(u.getUsername()+" deleted person "+p);
			} else throw new NumberFormatException();
		} catch(NumberFormatException e){
			response.getWriter().write(JSONMessage.errorMessage("Invalid parameters"));
		}
	}
	private void addPerson(HttpServletRequest request,
			HttpServletResponse response, UserAccount u)
			throws ServletException, IOException {
		PersonValidator validator = new PersonValidator(
			"0", 
			request.getParameter("firstname"),
			request.getParameter("lastname"),
			request.getParameter("identity"),
			request.getParameter("birthday")			
		);
		
		if(validator.isValid()){
			Person p = new Person(0, 
				validator.getFirstName(), 
				validator.getLastName(), 
				validator.getIdentity(), 
				validator.getBirthday(),
				u.getEmployee().getId(),
				u.getEmployee().getId(),
				new Date(),
				new Date()
			);
			ImbiConnection.getPersonDAO().insert(p);			
			Log.write(u.getUsername()+" created person "+p);			
		}		
		
		request.setAttribute("person", ImbiConnection.getPersonDAO().findAll());
		request.getRequestDispatcher("/WEB-INF/person.jsp").forward(request, response);
	}
}
